package name.zhengkeli.cloud.auth

import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.plugins.statuspages.*
import io.ktor.server.response.*
import kotlinx.serialization.Serializable

open class ServerException(val statusCode: HttpStatusCode, message: String? = null) : RuntimeException(message) {
    val typeName: String
        get() {
            if (this::class == ServerException::class)
                return "Unknown"
            val className = this::class.simpleName
            if (className == null)
                return "Unknown"
            if (className.endsWith("Exception"))
                return className.slice(0 until className.length - "Exception".length)
            return className
        }
}

@Serializable
data class ServerExceptionMessage(val type: String, val message: String? = null)

fun Application.configureExceptionHandler() {
    install(StatusPages) {
        exception<ServerException> { call, cause ->
            call.respond(cause.statusCode, ServerExceptionMessage(cause.typeName, cause.message))
        }
    }
}
